package dao

import (
	"net/http"

	"gitee.com/shuwenhe/shuwen/cart/model"
	"gitee.com/shuwenhe/shuwen/cart/util"
)

func GetSession(sessionID string) (*model.Session, error) { // 根据sessionID到数据库中查询session
	sql := "select session_id,username,user_id from session where session_id = ?"
	stmt, err := util.Db.Prepare(sql)
	if err != nil {
		return nil, err
	}
	session := &model.Session{}
	row := stmt.QueryRow(sessionID)
	row.Scan(&session.SessionID, &session.UserName, &session.UserID)
	return session, nil
}

func IsLogin(r *http.Request) (bool, *model.Session) {
	cookie, _ := r.Cookie("user")
	if cookie != nil {
		cookieValue := cookie.Value
		session, _ := GetSession(cookieValue)
		if session.UserID > 0 {
			return true, session // 已经登录
		}
	}
	return false, nil // 没有登录
}
